package cn.tedu.store.user.webapi.security;

import cn.tedu.store.commons.ex.ServiceException;
import cn.tedu.store.commons.pojo.user.vo.UserLoginInfoVO;
import cn.tedu.store.commons.web.ServiceCode;
import cn.tedu.store.user.webapi.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("security调用了loadUserByUsername() 参数:{}",s);
        //从数据库中查询用户信息
        UserLoginInfoVO loginInfo = userMapper.getLoginInfoByUsername(s);
        log.debug("loginInfo: {}",loginInfo);
        if(loginInfo == null){
            String message = "登录失败,用户名不存在!";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        List<GrantedAuthority> authorities = new ArrayList<>();
        GrantedAuthority authority = new SimpleGrantedAuthority("user");
        authorities.add(authority);
        //用户名存在,生成UserDetails并返回
        MyUserDetails userDetails = new MyUserDetails(loginInfo.getId(),
                loginInfo.getUsername(),loginInfo.getPassword(),
                loginInfo.getStatus() == 1,authorities
        );
        userDetails.setId(loginInfo.getId());
        log.debug("userDetails: {}",userDetails);
        return userDetails;
    }
}
